<template>
  <el-dialog v-model="dialogVisible" :close-on-click-modal="false" draggable title="Settings"
    :width="props.tagsname == 'Input' ? '70%' : '40%'" height="50rem">
    <el-form :model="form" label-width="auto" v-if="props.tagsname == 'Input'">
      <!-- <el-form-item label="keyType">
        <el-select v-model="form.keyType" placeholder="please select" @change="ground">
          <el-option label="Tag itself" value="2" />
          <el-option label="Formula" value="3" />
        </el-select>
      </el-form-item> -->
      <div class="el_box">
        <div class="el_box_left">
          <div class="searchBar">
            <el-input placeholder="TagName Or Description" v-model="getAllTagPrarms.keyword"></el-input>
            <el-button type="primary" @click="getAllTagByKeywordFun">Search</el-button>
            <el-button type="primary" style="margin-left: 0.5rem" @click="inquiryClick">Add
              New Tag</el-button>
          </div>
          <div class="tip-box">Double Click Each Row to Add New Tag</div>
          <el-table :data="allTagNameList" border stripe :header-cell-style="{ 'text-align': 'center' }" height="80%"
            @row-dblclick="copyRowToRight">
            <el-table-column prop="tagName" show-overflow-tooltip label="TagName" align="left" width="300">
            </el-table-column>
            <el-table-column prop="unit" label="Unit" align="center" show-overflow-tooltip
              width="100"></el-table-column>
            <el-table-column prop="remark" show-overflow-tooltip label="Description" align="left"></el-table-column>
          </el-table>
          <div class="page-box" style="padding-top: 0.5rem;">
            <custom-pagination style="text-align: left; justify-content: flex-start" :total="total"
              :page-count="pageCount" :current="currentPage" @pagination="handlePagination"></custom-pagination>
          </div>
        </div>
        <div class="el_box_right">
          <el-row>
            <el-col :span="24">
              <el-form-item label="TagName:">
                <el-input v-model="form.key" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="ValueColor:">
                <el-color-picker v-model="form.valueColor" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="ValueSize:">
                <el-input-number v-model="form.valueFontSize" :max="100" :min="10" style="width: 14rem; height: 2rem" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="Remark:">
                <el-input v-model="form.remark" type="textarea" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>
      <!-- <el-form-item label="key">
        <el-select v-model="form.key" filterable placeholder="please select">
          <el-option v-for="item in otherWellTagList" :key="item.id" :label="item.tagName" :value="item.tagName" />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="key">
        <div style="display: flex">
          <el-select v-if="form.keyType === '1'" v-model="form.key" filterable placeholder="please select"
            style="width: 32.5rem">
            <el-option v-for="item in tagTypesList" :key="item.key" :label="item.value" :value="item.key" />
          </el-select>
          <el-select v-else-if="form.keyType === '2'" v-model="form.key" filterable remote @focus="changelist"
            :remote-method="handleRemoteMethod" :loading="loading" ref="select" placeholder="Please select"
            style="width: 32.5rem">
            <el-option v-for="item in paginatedOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
            <el-pagination small @current-change="handlePageChange" :current-page="currentPage" :page-size="pageSize"
              :total="filteredOptions.length" layout="prev, pager, next">
            </el-pagination>
          </el-select>
          <el-button type="primary" v-if="form.keyType === '2'" style="margin-left: 0.5rem" @click="inquiryClick">Add
            New Tag</el-button>
        </div>
      </el-form-item> -->
      <!-- <el-form-item  label="valueColor">
        <el-color-picker v-model="form.valueColor" />
      </el-form-item>
      <el-form-item label="valueSize">
        <el-input-number v-model="form.valueFontSize" :max="100" :min="10" style="width: 10rem; height: 2rem" />
      </el-form-item>
      <el-form-item label="remark">
        <el-input v-model="form.remark" type="textarea" />
      </el-form-item> -->
    </el-form>
    <el-form :model="form" label-width="auto" style="max-width: 600px" v-if="props.tagsname == 'Formulas'">
      <el-form-item label="ValueSize:">
        <el-input-number v-model="form.valueFontSize" :max="100" :min="10" style="width: 15.5rem; height: 2rem" />
      </el-form-item>
      <el-form-item label="Formula:">
        <el-select v-model="form.formulaId" filterable placeholder="please select" style="width: 250px">
          <el-option v-for="option in formulaList" :key="option.id" :label="option.label" :value="option.value" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item v-show="form.keyType === '3'" label="text">
        <el-input v-model="form.formulaText" />
      </el-form-item>
      <el-form-item v-for="(item, index) in formulaBindTagList" v-show="form.keyType === '3'" :key="index"
        :label="item.name">
        <el-select v-model="item.tagName" filterable placeholder="please select" style="width: 300px"
          @change="onSelectTagName(item, index)">
          <el-option v-for="option in tagsList" :key="option.id" :label="option.tagName" :value="option.tagName" />
        </el-select>
        <el-icon v-if="index === formulaBindTagList.length - 1" size="20" style="padding: 10px; cursor: pointer"
          @click="addFormulaTag">
          <CirclePlusFilled />
        </el-icon>
        <el-icon v-else size="20" style="padding: 10px; cursor: pointer" @click="removeFormulaTag(index)">
          <RemoveFilled />
        </el-icon>
      </el-form-item> -->
    </el-form>
    <el-form :model="form" label-width="auto" style="max-width: 600px" v-if="props.tagsname == 'Text'">
      <el-row>
        <el-col :span="12">
          <el-form-item label="ValueColor:">
            <el-color-picker v-model="form.valueColor" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="ValueSize:">
            <el-input-number v-model="form.valueFontSize" :max="100" :min="10" style="width: 14rem; height: 2rem" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="Remark:">
            <el-input v-model="form.remark" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="confirm">Confirm</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog title="Add New Tag" v-model="fuzzyQuery" :before-close="handleClose"
    style="width: 36%; height: 76%; top: -2rem">
    <el-form-item label="Tag Name">
      <div style="display: flex; align-items: center">
        <el-input v-model="inputValue" placeholder="Please enter" style="flex: 1; margin-right: 5px; width: 300px"
          @input="redchange"></el-input>
        <el-button type="primary" :disabled="inputValue.length < 8" @click="search">Search</el-button>
      </div>
    </el-form-item>
    <p style="color: red; margin-left: -7rem">
      Enter more than eight characters to find the corresponding Tag
    </p>
    <el-form-item>
      <el-table :data="tablePaginatedData" @row-click="handleEdit" style="width: 100%" height="27.5rem" border
        highlight-current-row>
        <el-table-column type="index" align="center" label="No."></el-table-column>
        <el-table-column prop="tagName" label="Tag Name" align="center"></el-table-column>
        <el-table-column prop="units" label="Units" align="center"></el-table-column>
        <el-table-column prop="description" label="Description" align="center"></el-table-column>
      </el-table>
      <el-pagination small @current-change="handleTablePageChange" :current-page="tableCurrentPage"
        :page-size="tablePageSize" :total="tableTotal" layout="prev, pager, next, ->, total" class="pagination-right">
      </el-pagination>
    </el-form-item>
    <span class="dialog-footer">
      <el-button @click="fuzzyQuery = false">Cancel</el-button>
      <el-button type="primary" :disabled="!isRowClicked" @click="submitAdd">Submit</el-button>
    </span>
  </el-dialog>
</template>
<script>
import CustomPagiation from "@/components/customPagiation.vue";
export default {
  components: { 'custom-pagination': CustomPagiation },
}
</script>
<script setup>
import {
  computed,
  defineEmits,
  defineModel,
  defineProps,
  ref,
  watchEffect,
  onMounted
} from "vue";
import {
  getWellTag,
  getAllWellTag,
  getAllTagByName,
  wellTagManageAdd,
  getAllTagByKeyword,
  getFormulaDrop
} from "@/api";
import { ElLoading, ElMessage, ElMessageBox, progressProps } from "element-plus";
import { CirclePlusFilled, RemoveFilled } from "@element-plus/icons-vue";
const dialogVisible = defineModel();
const props = defineProps([
  "wellId",
  "formValue",
  "tagsList",
  "formulaList",
  "tagTypesList",
  "list",
  "fTag",
  "tageData",
  "uuidList",
  "tagsname"
]);
const emit = defineEmits(["confirm"]);
const otherWellTagList = ref([]);
const apiTagsList = ref([]);
const form = ref({});
const formulaTag = ref({});
const wellid = props;
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const filteredOptions = ref([]);
const paginatedOptions = ref([]);
const cunwent = ref("");
const descDateil = ref({});
const fuzzyQuery = ref(false);
// 新增的输入框和下拉框绑定的数据
const inputValue = ref("");
// 修改为分页后的数据
const tableData = ref([]);
const originalTableData = ref([]);
const getAllTagPrarms = ref({
  keyword: '',
  page: 1, // 分页参数：当前页
  pageSize: 15 // 分页参数：每页条数
});
const allTagNameList = ref([]); // 表格数据
const total = ref(0); // 总条数
const pageCount = ref(0); // 总页数
const boxForm = ref({
  name: '',
  color: '#409EFF',
  number: 50,
  description: ''
})
// 新增分页相关数据
const tableCurrentPage = ref(1);
const tablePageSize = ref(10);
const tableTotal = ref(tableData.value.length);
const tablePaginatedData = computed(() => {
  const start = (tableCurrentPage.value - 1) * tablePageSize.value;
  const end = tableCurrentPage.value * tablePageSize.value;
  return tableData.value.slice(start, end);
});
// 新增的变量用于跟踪表格行的点击状态
const isRowClicked = ref(false);

watchEffect(() => {
  form.value = { ...props.formValue };
  formulaTag.value = { ...props.fTag };
});

const formulaBindTagList = computed(() => {
  return Object.entries(formulaTag.value).map(([name, tagName]) => ({
    name,
    tagName,
  }));
});

const addFormulaTag = () => {
  const maxAttempts = 10;
  const tagNames = Object.keys(formulaTag.value);
  for (let i = 0; i < maxAttempts; i++) {
    if (!tagNames.includes(`t${i}`)) {
      formulaTag.value[`t${i}`] = "";
      break;
    }
  }
};

const onSelectTagName = (a) => {
  formulaTag.value = formulaBindTagList.value.reduce((acc, item) => {
    acc[item.name] = item.tagName;
    return acc;
  }, {});
};

const getOtherWellTag = () => {
  form.value.key = null;
  getWellTag(form.value.otherWellId).then((res) => {
    if (res?.code === 200) {
      res.data.sort(
        (a, b) => a.tagName.toUpperCase() - b.tagName.toUpperCase()
      );
      otherWellTagList.value = res.data || [];
    }
  });
};

const ground = () => {
  if (form.value.keyType === "2") {
    form.value.key = null;
    // 调用接口获取数据
    getAllWellTag().then((res) => {
      if (res.code === 200) {
        const uniqueTags = new Set();
        apiTagsList.value = res.data
          .filter((item) => {
            const tagName = item.tagName;
            if (!uniqueTags.has(tagName)) {
              uniqueTags.add(tagName);
              return true;
            }
            return false;
          })
          .map((item) => ({
            label: item.tagName,
            value: item.tagName,
            desc: item.remark,
            unit: item.unit
          }));
        filteredOptions.value = apiTagsList.value;
        currentPage.value = 1;
        updatePaginatedOptions();
      }
    });
  } else if (form.value.keyType === '3') {
    let set_a = JSON.parse(JSON.stringify(props));
    set_a.uuidList.forEach((element) => {
      if (element.id === form.value.id) {
        console.log(element);

        // form.value.formulaId = element.id
      }
    });
  } else {
    set_a.uuidList.forEach((element) => {
      if (element.id === form.value.id) {
        form.value.formulaText = element.formula.formulaText;
        const value = Object.entries(element.formula.formulaTag).map(
          ([name, tagName]) => ({
            name,
            tagName,
          })
        );
        const formulaTagObject = value.reduce((acc, item) => {
          acc[item.name] = item.tagName;
          return acc;
        }, {});
        formulaTag.value = formulaTagObject;
      }
    });
  }
};

const removeFormulaTag = (index) => {
  const tagNames = Object.keys(formulaTag.value);
  const tagNameToRemove = tagNames[index];
  delete formulaTag.value[tagNameToRemove];
};
const copyRowToRight = (row) => {
   form.value.key = row.tagName
}
const confirm = () => {
  descDateil.value = apiTagsList.value.filter((item) => item.label == form.value.key)[0];
  emit("confirm", { form: form.value, formulaTag: formulaTag.value, ...descDateil.value });
};
const redchange = (val) => {
  if (originalTableData.value.length != 0) {
    if (val === "") {
      tableData.value = [];
    } else {
      const result = originalTableData.value.filter((item) =>
        item.tagName.includes(val)
      );
      tableData.value = result;
    }
    isRowClicked.value = false;
    tableTotal.value = tableData.value.length;
    const start = (tableCurrentPage.value - 1) * tablePageSize.value;
    const end = tableCurrentPage.value * tablePageSize.value;
    tablePaginatedData.value = tableData.value.slice(start, end);
    // 新增代码：移除表格当前选中行的样式类
    const table = document.querySelector(".el-table__body-wrapper");
    if (table) {
      const currentRow = table.querySelector(".current-row");
      if (currentRow) {
        currentRow.classList.remove("current-row");
      }
    }
  }
};
const changelist = () => {
  ground();
};
const handleRemoteMethod = (query) => {
  if (query !== "") {
    loading.value = true;
    setTimeout(() => {
      filteredOptions.value = apiTagsList.value.filter((item) =>
        item.label.toLowerCase().includes(query.toLowerCase())
      );
      currentPage.value = 1; // Reset to first page
      updatePaginatedOptions();
      loading.value = false;
    }, 200);
  } else {
    filteredOptions.value = apiTagsList.value;
    currentPage.value = 1; // Reset to first page
    updatePaginatedOptions();
  }
};

const updatePaginatedOptions = () => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = currentPage.value * pageSize.value;
  paginatedOptions.value = filteredOptions.value.slice(start, end);
};

const handlePageChange = (page) => {
  currentPage.value = page;
  updatePaginatedOptions();
};

// 新增的 inquiryClick 方法
const inquiryClick = () => {
  inputValue.value = "";
  tableData.value = "";
  fuzzyQuery.value = true;
  // 重置点击状态
  isRowClicked.value = false;
};

const handleClose = () => {
  // 可以在这里添加关闭弹窗时的逻辑
  fuzzyQuery.value = false;
};

// 新增表格分页方法
const updateTablePaginatedOptions = () => {
  const start = (tableCurrentPage.value - 1) * tablePageSize.value;
  const end = tableCurrentPage.value * tablePageSize.value;
  tablePaginatedData.value = tableData.value.slice(start, end);
};

const handleTablePageChange = (page) => {
  tableCurrentPage.value = page;
  updateTablePaginatedOptions();
};

// 新增的 search 方法
const search = () => {
  // 在这里编写搜索的具体逻辑
  console.log("执行搜索操作", inputValue.value);
  let formData = new FormData();
  formData.append("tagName", inputValue.value);
  getAllTagByName(formData).then((res) => {
    if (res.code == 200) {
      console.log(tableData, "搜索tagname 得到的描述");
      tableData.value = res.data;
      originalTableData.value = res.data; // 保存原始数据
      tableTotal.value = tableData.value.length;
      const start = (tableCurrentPage.value - 1) * tablePageSize.value;
      const end = tableCurrentPage.value * tablePageSize.value;
      tablePaginatedData.value = tableData.value.slice(start, end);
      isRowClicked.value = false;
    } else {
      ElMessage.error(res.msg);
    }
  });
};
const getAllTagByKeywordFun = () => {
  getAllTagByKeyword(getAllTagPrarms.value).then(res => {
    if (res.code === 200) {
      total.value = res.data.total;
      getAllTagPrarms.value.page = res.data.page;
      getAllTagPrarms.value.pageSize = res.data.pageSize;
      allTagNameList.value = res.data.records || [];
      pageCount.value = res.data.pages;
    } else {
      ElMessage.error(res.msg || '获取数据失败');
    }
  }).catch(err => {
    ElMessage.error('请求出错，请稍后重试');
    console.error(err);
  });
};
const handlePagination = (pagination) => {
  getAllTagPrarms.value.pageSize = pagination.pageSize
  getAllTagPrarms.value.page = pagination.page
  currentPage.value = pagination.page
  getAllTagByKeywordFun()
}

// 组件挂载后自动调用，初始加载数据
onMounted(() => {
  getAllTagByKeywordFun();
  // copyRowToRight();
});
//弹窗提交
const submitAdd = () => {
  let params = {
    unit: "",
    common: 0,
    dataCompletion: 0,
    tagType: -1,
    remark: "",
    getTagWay: 0,
    wellId: wellid.wellId,
    tagName: cunwent.value,
  };
  wellTagManageAdd(params).then((res) => {
    if (res.code == 200) {
      fuzzyQuery.value = false;
      tableTotal.value = 0;
      const start = 1;
      const end = 1;
      tablePaginatedData.value = tableData.value.slice(start, end);
      ground();
    } else {
      ElMessage.error(res.msg);
      fuzzyQuery.value = false;
    }
  });
};

//表格单击
//表格单击
const handleEdit = (row) => {
  cunwent.value = row.tagName;
  // 更新点击状态
  isRowClicked.value = true;
  // 新增代码：切换当前行的样式
  // const table = document.querySelector('.el-table__body-wrapper');
  // if (table) {
  //   const currentRow = table.querySelector('.current-row');
  //   if (currentRow) {
  //     currentRow.classList.remove('current-row');
  //   }
  //   const targetRow = table.querySelector(`[data-row-index="${row._rowIndex}"]`);
  //   if (targetRow) {
  //     targetRow.classList.add('current-row');
  //   }
  // }
};
</script>

<style scoped>
.el_box {
  padding: 5px;
  border-radius: 4px;
  display: flex;
}

.tip-box {
  text-align: left;
  height: 1.2rem;
  color: red;
}

::v-deep .el-table .el-table__cell {
  padding: 0.24rem 0rem;
}

::v-deep .el-pagination button {
  height: 1.5rem;
}

.el_box_left {
  width: 50%;
  height: 100%;
  border-right: 1px solid #a1a1a1;
  padding-right: 0.3rem;
}

.searchBar {
  display: flex;
  flex-direction: row;
  margin-bottom: 0.5rem
}

.el_box_right {
  width: 48%;
  height: 100%;
  display: flex;
  margin-top: 2.7rem;
  margin-left: 0.5rem;
}

.el-dialog__body {
  padding: 24px;
}

/* .el-form {
  margin: 0 auto;
} */

.el-form-item {
  margin-bottom: 16px;
}

.el-form-item__label {
  min-width: 80px;
  text-align: right;
  padding-right: 12px;
}

.el-select,
.el-input-number,
.el-input {
  width: 100%;
  max-width: 320px;
}

.dialog-footer {
  gap: 12px;
}

.pagination-right {
  margin-top: 16px;
}

.el-table {
  --el-table-padding-vertical: 12px;
  --el-table-padding-horizontal: 16px;
}

.el-form-item .el-input {
  align-self: center;
}

.dialog-footer {
  text-align: right;
  display: flex;
  justify-content: flex-end;
}

.pagination-right {
  display: flex;
  justify-content: flex-end !important;
}

::v-deep .el-table__body tr.current-row>td.el-table__cell {
  background-color: rgb(209 226 244);
}

.demo-form {
  max-width: 600px;
  /* margin: 0 auto; */
  padding: 20px;
}
</style>